// +----------------------------------------------------------------------
// | CmsWing [ 美业管理系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016 psi All rights reserved.
// +----------------------------------------------------------------------
// | Author: huang <2374266244@qq.com>
// +----------------------------------------------------------------------
'use strict';
import Base from './base.js';

export default class extends Base {
  /**
   * index action
   * @return {Promise} []
   */
  async userlistAction() {
    // 取出当前店的员工

    const page = JSON.parse(this.post('page'));
    const pages = page.pages;
    const limits = page.limits;
    const search = page.search;
    const shopid = this.shop_userinfo.departmentid;

    const where = {
      'u.shopid': shopid,
      'u.isdisable': page.zt,
      'u.isdelete': 0,
      'u.username|u.name|u.worknum': ['like', '%' + search + '%']
    };

    const data = await this.model('or_app_user')
      .alias('u')
      .field('u.id,u.username,u.name,u.ismanage,u.sex,u.isdisable, u.remarks,d.name as departmentname,d.id as departmentid,p.name as positionname, p.id as pid,s.name as zhichengname, s.id as sid,u.addtime,u.xiaozuid,u.bumenid,u.departmentid,u.worknum')
      .join('think_or_department d ON u.departmentid = d.id')
      .join('think_or_position p ON u.positionid = p.id')
      .join('think_or_position s ON u.zhichengid = s.id')
      .where(where)
      .page(pages, limits)
      .order('u.id DESC')
      .countSelect();

    return this.json(data);
  }

  async adduserAction() {
    const data = this.post();
    const addtime = Math.round(new Date().valueOf() / 1000);
    const shopid = this.shop_userinfo.departmentid;
    // 判断当前分店员工工号是否重复
    const repeatWorknum = await this.model('or_app_user').where({isdelete: 0, shopid: shopid, worknum: data.worknum}).find();
    if (!think.isEmpty(repeatWorknum)) {
      return this.fail('工号重复');
    }
    // 取机构id（机构唯一）标准#010
    const orcode = await this.model('or_department').where({id: shopid}).getField('orcode', true);
    const isExist = await this.model('or_app_user')
      .alias('u')
      .join('`think_or_department` d on u.departmentid = d.id')
      .where({isdelete: 0, username: data.username, orcode: orcode})
      .find();

    if (!think.isEmpty(isExist)) {
      return this.fail('该登陆账号已经存在！');
    }

    const bumenInfo = await this.model('or_department').where({id: data.departmentid}).find();

    switch (bumenInfo.floor) {
      case 1:
        data.bumenid = 0;
        data.xiaozuid = 0;
        break;
      case 2:
        data.bumenid = bumenInfo.id;
        data.xiaozuid = 0;
        break;
      case 3:
        data.bumenid = bumenInfo.pid;
        data.xiaozuid = bumenInfo.id;
        break;
    }

    data.password = think.md5(data.username);
    data.addtime = addtime;
    data.shopid = this.shop_userinfo.departmentid;

    const res = await this.model('or_app_user').add(data);
    return res ? this.success('添加成功！') : this.fail('添加失败！');
  }

  // 编辑当前用户
  async edituserAction() {
    const data = this.post();
    // 取机构id（机构唯一）标准#010
    const repeatWorknum = await this.model('or_app_user')
      .alias('ap')
      .join('`think_or_app_user` au on au.id = ap.id')
      .where({'ap.isdelete': 0, 'ap.departmentid': data.departmentid, 'au.worknum': data.worknum, 'ap.id': ['!=', data.id]})
      .find();
    if (!think.isEmpty(repeatWorknum)) {
      return this.fail('工号重复');
    }
    const orcode = await this.model('or_app_user')
      .alias('u')
      .join('`think_or_department` d on u.departmentid = d.id')
      .where({'u.id': data.id})
      .getField('d.orcode', true);
    const isExist = await this.model('or_app_user')
      .alias('u')
      .join('`think_or_department` d on u.departmentid = d.id')
      .where({'u.isdelete': 0, username: data.username, orcode: orcode, 'u.id': ['!=', data.id]})
      .find();
    if (!think.isEmpty(isExist)) {
      return this.fail('该登陆账号已经存在！');
    }

    const bumenInfo = await this.model('or_department').where({id: data.departmentid, isdisable: 0}).find();

    if (!bumenInfo.id) {
      return this.fail('该部门已关闭，请重新选择部门！');
    }
    switch (bumenInfo.floor) {
      case 1:
        data.bumenid = 0;
        data.xiaozuid = 0;
        break;
      case 2:
        data.bumenid = bumenInfo.id;
        data.xiaozuid = 0;
        break;
      case 3:
        data.bumenid = bumenInfo.pid;
        data.xiaozuid = bumenInfo.id;
        break;
    }

    data.password = think.md5(data.username);
    data.remarks = data.remarks ? data.remarks : (data.remarks = '无');
    data.isdisable = 0;
    const res = await this.model('or_app_user').update(data);
    return res ? this.success('编辑成功！') : this.fail('编辑失败！');
  }

  // 停用、启用当前用户
  // 一旦弃用将不再显示
  async unstopAction() {
    const id = this.post('id');
    const model = this.model('or_app_user');
    await model.transaction(async() => {
      try {
        const you = await this.model('or_allotuser').db(model.db()).where({uid: id}).select();
        if (!think.isEmpty(you)) {
          const shanchu = await this.model('or_allotuser').db(model.db()).where({uid: id}).delete();
          if (!shanchu) {
            await model.rollback();
            return this.fail('停职失败');
          }
        }

        const res = await model.where({id: id}).update({isdisable: 1, ismanage: 0, worknum: ''});
        if (!res) {
          await model.rollback();
          return this.fail('停职失败');
        }

        await model.commit();
        return this.success('停职成功');
      } catch (e) {
        await model.rollback();
        return this.fail('停职失败');
      }
    });
  }

  // 修改员工所在部门，如果当前员工为管理层，则取消其管理层权限，（ismanage : 0）
  async edituserdepartmentAction() {
    if (this.isPost) {
      const editData = this.post();
      editData.ismanage = 0;
      editData.departmentid = editData.depid;
      const bumenInfo = await this.model('or_department').where({id: editData.depid}).find();
      switch (bumenInfo.floor) {
        case 1:
          editData.bumenid = 0;
          editData.xiaozuid = 0;
          break;
        case 2:
          editData.bumenid = bumenInfo.id;
          editData.xiaozuid = 0;
          break;
        case 3:
          editData.bumenid = bumenInfo.pid;
          editData.xiaozuid = bumenInfo.id;
          break;
      }
      const data = await this.model('or_app_user').where({id: editData.id}).update(editData);
      return data ? this.success({info: '修改部门成功'}) : this.fail('修改部门失败');
    }
    const curdepartmentid = this.shop_userinfo.departmentid;
    const departments = await this.model('or_department').where({pid: curdepartmentid, isdisable: 0}).select();
    const did = await this.model('or_department').where({id: curdepartmentid}).find();
    const groups = [];
    if (departments.length) {
      for (var i = 0, depLen = departments.length; i < depLen; i++) {
        groups.push(await this.model('or_department').where({pid: departments[i].id, isdisable: 0}).select());
      }
    }
    departments.push(did);
    const shops = {
      dep: departments,
      gro: groups
    };
    return this.json(shops);
  }

  // 获取顾客分配人员信息列表
  async allotusersAction() {
    const guestid = this.post('guestid');
    const userlist = await this.model().query('select u.id,u.name,u.username,zw.name as zhiwei,zc.name as zhicheng,d.name as dname,d.id as did,u.bumenid,u.xiaozuid from `think_or_app_user` as u left join `think_or_allotuser` a on u.id=a.uid left join `think_or_position` zw on u.positionid=zw.id left join `think_or_position` zc on zc.id=u.zhichengid left join `think_or_department` d on d.id=u.departmentid where a.gid=' + guestid);
    return this.json(userlist);
  }

  // 查看用户信息
  async userinfoAction() {
    const id = this.post('id');
    const info = await this.model('or_app_user').where({id: id}).find();
    return this.json(info);
  }

  // 重置当前员工帐号和密码
  async resetpasswordAction() {
    const uid = this.get('id');

    const uinfo = await this.model('or_app_user').where({id: uid}).find();

    const password = think.md5(uinfo.username);

    const resetRes = await this.model('or_app_user').where({id: uid}).update({password: password});

    return resetRes ? this.success('重置员工密码成功') : this.fail('重置员工密码失败');
  }

  // 获取当前分店所有有效部门和小组列表
  async getdepartmentlistAction() {
    const shopid = this.shop_userinfo.departmentid;

    const shop = await this.model('or_department').where({id: shopid}).find();

    const bumens = await this.model('or_department').where({pid: shopid, isdisable: 0}).select();

    const groups = await this.model('or_department')
      .alias('x')
      .field('x.*')
      .join('`think_or_department` b on b.id=x.pid')
      .where({'b.pid': shopid, 'x.isdisable': 0})
      .select();

    const data = {
      shop: shop,
      bumens: bumens,
      groups: groups
    };

    return this.json(data);
  }
}
